/*
 * @Author: HZK
 * @Date: 2020-09-17 14:12:22
 * @LastEditTime: 2020-12-01 16:57:21
 * @LastEditors: hanfengmi
 * @Description: 
 */
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base.js'); // 引用公共的配置
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 用于将组件的css打包成单独的文件输出到`lib`目录中
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const prodConfig = {
  mode: 'production', // 开发模式
  entry: path.join(__dirname, "../app.js"),
	output: {
    path: path.join(__dirname, "../lib/"),
    filename: "[name].[hash].js",
    libraryTarget: 'umd', // 采用通用模块定义, 注意webpack到4.0为止依然不提供输出es module的方法，所以输出的结果必须使用npm安装到node_modules里再用，不然会报错
    libraryExport: 'default', // 兼容 ES6(ES2015) 的模块系统、CommonJS 和 AMD 模块规范
  },
	module: {
		rules: [
      {
        test: /\.css$/,
        use:[MiniCssExtractPlugin.loader,{
          loader:'css-loader',
          options: {
              modules: {
                  localIdentName: '[local]-[name]-[hash:base64:5]'
              },
            }
        },'postcss-loader'],
        exclude:[/node_modules/],
      },
      {
        test: /\.css$/,
        use: ['style-loader','css-loader'],
        exclude:[/src/],
      },
      {
        test:/\.less$/,
        use:[MiniCssExtractPlugin.loader,{
            loader:'css-loader',
            options: {
                modules: {
                    localIdentName: '[local]-[name]-[hash:base64:5]'
                },
              }
        },'postcss-loader','less-loader'],
        exclude: /node_modules/
      },
    ]
  },
  optimization:{
    splitChunks: {
      chunks: 'initial',
      automaticNameDelimiter: '.',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: 1
        }
      }
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env.prod" : JSON.stringify('prod')
    }),
    new MiniCssExtractPlugin({
      filename: 'main.css',
      chunkFilename: 'main.css',
      disable: false, //是否禁用此插件
      allChunks: true,
    }),
    new UglifyJSPlugin({
      sourceMap: false,
    }),
    new CleanWebpackPlugin(),
    new BundleAnalyzerPlugin()
  ],
  externals: { // 定义外部依赖，避免把react和react-dom打包进去
    react: {
      root: "React",
      commonjs2: "react",
      commonjs: "react",
      amd: "react"
    },
    "react-dom": {
      root: "ReactDOM",
      commonjs2: "react-dom",
      commonjs: "react-dom",
      amd: "react-dom"
    }
  }
};

module.exports = merge(prodConfig, baseConfig); // 将baseConfig和prodConfig合并为一个配置
